package net

import (
	"fmt"
	"github.com/valyala/fasthttp"
	"net"
)

type Server struct {
	ln net.Listener
}

func validation(ctx *fasthttp.RequestCtx) {
	ctx.WriteString("ok")
}

func requestHandler(ctx *fasthttp.RequestCtx) {
	path := string(ctx.Path())
	method := string(ctx.Method())

	switch {
	case path == "/api/v1/msg" && method == "GET":
		validation(ctx)
	case path == "/api/v1/msg2" && method == "POST":
		//setLogLevel(ctx)
	default:
		ctx.SetStatusCode(404)
	}
}

//TODO 参数从配置文件当中获取，修改输出日志
func (s *Server) Start() {
	addr := "localhost:8081"
	srv := &fasthttp.Server{
		Handler: requestHandler,
		Name:    "Terminal Push Router Server",
	}
	ln, err := net.Listen("tcp4", addr)
	if err != nil {
		fmt.Printf("Terminal Push server: Listening on %s with error: %s\n", addr, err)
		return
	}
	fmt.Printf(" serve listening on %s\n", addr)
	s.ln = ln
	//go func() {
	if err := srv.Serve(ln); err != nil {
		fmt.Printf(" server: Served) with error: %s\n", err)
	}
	//}()
}

func (s *Server) Close() error {
	ln := s.ln
	if ln != nil {
		s.ln = nil
		fmt.Printf("Terminal Push server stopped\n")
		return ln.Close()
	}
	return nil
}
